package com.sparkseries.common.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sparkseries.common.security.domain.SecurityUser;
import com.sparkseries.common.security.util.JwtUtil;
import com.sparkseries.common.util.domain.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 打印登录成功后的JWT
     * @param request : 请求对象
     * @param response : 应答对象
     * @param authentication : Spring Security 框架验证用户信息成功后的封装类
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 对用户信息进行收集
        SecurityUser user = (SecurityUser) authentication.getPrincipal();

        // 将用户映射为String
        String userInfo = objectMapper.writeValueAsString(user);

        // 生成jwt
        String jwt = jwtUtil.createJwt(userInfo);

        stringRedisTemplate.opsForValue().set("loginToken:" + jwt, objectMapper.writeValueAsString(authentication), 2, TimeUnit.HOURS);

        printToken(response, Result.ok("用户登录成功", jwt));
    }

    // 打印Token
    private void printToken(HttpServletResponse response, Result<String> result) throws IOException {
        String strResult = objectMapper.writeValueAsString(result);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter writer = response.getWriter();
        writer.println(strResult);
        writer.flush();
        writer.close();
    }
}
